package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javabean.Product;
import com.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductService productService;

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, @RequestParam(value = "page",defaultValue = "1") int page,@RequestParam(value = "limit",defaultValue = "5")  int limit,@RequestParam(value = "productName",defaultValue = "")String productName){
        PageHelper.startPage(page,limit);
        List<Product> all = productService.findProductName(productName);
        PageInfo<Product> pageInfo=new PageInfo<>(all);

        request.setAttribute("pageInfo",pageInfo);
        request.setAttribute("value", productName);
        return "/product/product-list";
    }
    @RequestMapping("/findById")
    public String findById(HttpServletRequest request,int id){
        Product product = productService.findById(id);
        request.setAttribute("product",product);
        return "/product/product-edit";
    }

    @RequestMapping("/edit")
    public String edit(Product product){
        productService.edit(product);
        return "redirect:findAll";
    }
    @RequestMapping("/add")
    public String add(Product product){
        productService.add(product);
        return "redirect:findAll";
    }
    @RequestMapping("/show")
    public String show(HttpServletRequest request,int id){
        Product product = productService.findById(id);
        request.setAttribute("product",product);
        return "/product/product-show";
    }
    @RequestMapping("/deleteById")
    public String deleteById(int id){
        productService.deleteById(id);
        return "redirect:findAll";
    }

    @RequestMapping(value = "/deleteIds",method = RequestMethod.POST)
    @ResponseBody
    public String deleteIds(@RequestBody List<Integer> ids){
        productService.deleteIds(ids);
        return "/product/findAll";
    }
}
